package test;


import ans.base.ArgGen;
import com.fasterxml.jackson.databind.ObjectMapper;
import gen.Question;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Method;

public class ClassExec {
    public static final String BATH = System.getProperty("user.dir") + "/src/main/java/ans/";


    public static void execSolution(String url, Object... args) {
        url = url.replaceAll("/problems/(.*?)/.*", "/problems/$1");
        url = "\"" + url + "\"";
        try (BufferedReader bf = new BufferedReader(new FileReader("question_list.txt"))) {
            String line = null;
            while ((line = bf.readLine()) != null) {
                if (line.contains(url)) {
                    ObjectMapper obj = new ObjectMapper();
                    Question question = obj.readValue(line, Question.class);
                    String folderName = question.getFolderName();
                    Class<?> clazz = Class.forName("ans." + folderName + ".Solution");

                    Object o = clazz.newInstance();

                    Method[] methods = clazz.getMethods();

                    for (Method method : methods) {
                        if (method.isAnnotationPresent(Entrance.class)) {
                            Class[] parameterTypes = method.getParameterTypes();
                            //对数组的 直接由String构造
                            for (int i = 0; i < args.length; i++) {
                                if (args[i].getClass().equals(String.class) && !parameterTypes[i].equals(String.class)) {
                                    args[i] = ArgGen.gen(args[i].toString(), parameterTypes[i]);
                                }
                            }

                            Object invoke = method.invoke(o, args);
                            if (invoke != null) {
                                System.out.println(invoke);
                            } else {
                                System.out.println(">> end");
                            }
                        }
                    }
                    break;

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        execSolution("https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number", "23");

    }

}
